﻿using System;
using System.IO;
using System.Web;
using System.Windows.Forms;
using EasyHttp.Http;
using Newtonsoft.Json;

namespace DGRobot
{
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class QAFrm : Form
    {
        public QAFrm()
        {
            InitializeComponent();
            StartRobot();
        }
        DateTime lastHasWord = DateTime.Now;
        public void StartRobot()
        {
            RobotDriver.Instance.OnSpeakStart = RobotDriver_OnSpeakStart;
            RobotDriver.Instance.OnListenStart = RobotDriver_OnListenStart;
            RobotDriver.Instance.OnSpeakCompleted = RobotDriver_OnSpeakCompleted;
            RobotDriver.Instance.OnListening = RobotDriver_OnListening;
            RobotDriver.Instance.OnListenCompleted = RobotDriver_OnListenCompleted;
            lastHasWord = DateTime.Now;
            timer1.Start();
            
        }
        public void StopRobot()
        {
            RobotDriver.Instance.StopSpeak(false);
            RobotDriver.Instance.StopListen();
            timer1.Stop();
        }

        private void RobotDriver_OnListenCompleted(RobotDriver.ListenCompletedEventArgs args)
        {
            Invoke(new MethodInvoker(() =>
            {
                if (!string.IsNullOrEmpty(args.HearTheWord))
                {
                    lastHasWord = DateTime.Now;
                }
                else
                {
                    if ((DateTime.Now - lastHasWord).TotalMinutes<3)
                    {
                        StartNewRecord();
                        return;
                    }
                    lastHasWord = DateTime.Now;
                }
                InvokeScript("setCurrentQuestion", args.HearTheWord);
            }));
        }

        private void RobotDriver_OnListening(RobotDriver.ListeningEventArgs args)
        {
            Invoke(new MethodInvoker(() =>
            {
                if (!string.IsNullOrEmpty(args.HearTheWord))
                    lastHasWord = DateTime.Now;
                InvokeScript("recording",args.HearTheWord);
            }));
        }
        
        private void RobotDriver_OnSpeakCompleted(RobotDriver.SpeakCompletedEventArgs args)
        {
            Invoke(new MethodInvoker(() =>
            {
                InvokeScript("endSpeak");
            }));
            StartNewRecord();
        }

        private void RobotDriver_OnListenStart(RobotDriver.ListenStartEventArgs args)
        {
            Invoke(new MethodInvoker(() =>
            {
                this.picRobotState.Image = global::DGRobot.Properties.Resources.record;
                this.picRobotState.Tag = "listen";
            }));
        }

        private void RobotDriver_OnSpeakStart(RobotDriver.SpeakStartEventArgs args)
        {
            Invoke(new MethodInvoker(() =>
            {
                this.picRobotState.Image = global::DGRobot.Properties.Resources.speak;
                this.picRobotState.Tag = "speak";
            }));
        }
        
       
        private HtmlDocument htmlDocument;

        private void QAFrm_Load(object sender, EventArgs e)
        {
            // 将当前类设置为可由脚本访问
            this.webBrowser1.ObjectForScripting = this;
            this.webBrowser1.Url = new Uri(Path.Combine(Environment.CurrentDirectory, "wwwroot/QA_index.html"));
            htmlDocument = this.webBrowser1.Document;

            //this.webBrowser1.
        }
        
       
        /// <summary>
        /// 供js调用
        /// </summary>
        /// <param name="text"></param>
        public void SpeakText(string text)
        {
            if (string.IsNullOrEmpty(text)) return;

            RobotDriver.Instance.StartSpeak(nameof(QAFrm), text);
        }

        public void OutputRecordWord(string text)
        {
            Invoke(new MethodInvoker(() =>
            {
                InvokeScript("recording",text); 
            }));
        }
        public void StartNewRecord()
        {
            //开始下一次说
            RobotDriver.Instance.StartListen(nameof(QAFrm));
            Invoke(new MethodInvoker(() =>
            {
                InvokeScript("startRecord");
            }));
        }
        public void EndRecord()
        {
            RobotDriver.Instance.StopListen();
            Invoke(new MethodInvoker(() =>
            {
                InvokeScript("endRecord");
            }));
        }
        public void StopCurrentSpeak()
        {
            RobotDriver.Instance.StopSpeak();
        }


        public void ProcessBeforePara(string para)
        {
            var actionPara = JsonConvert.DeserializeObject<QuestionActionPara>(para);
            if (actionPara == null || string.IsNullOrEmpty(actionPara.Action)) return;
            switch (actionPara.Action)
            {
                case QuestionActionPara.Action_StopSpeak:
                    StopCurrentSpeak();
                    break;
                case QuestionActionPara.Action_StopSpeakAndPop:
                    StopCurrentSpeak();
                    ProcessPara(para);
                    break;
                case QuestionActionPara.Action_Pop:
                    ProcessPara(para);
                    break;
            }
        }
        public void ProcessPara(string para)
        {
            var actionPara = JsonConvert.DeserializeObject<QuestionActionPara>(para);
            if (actionPara == null) return;

            if (actionPara.Type == QuestionActionPara.Type_OpenPdf)
            {
                var file = new FileInfo(actionPara.Value);
                if (file.Exists == false)
                {
                    MessageBox.Show("文档不存在: " + para);
                    return;
                }
                PdfViewFrm pdfView = new PdfViewFrm();
                pdfView.SetPdfPath(file.FullName);
                pdfView.ShowDialog();
            }
            else if (actionPara.Type == QuestionActionPara.Type_OpenUrl)
            {
                var view = new UrlViewFrm();
                view.SetUrlPath(Config.TbmServerUrl + actionPara.Value +"?searchKey="+HttpUtility.UrlEncode(actionPara.Answer));
                view.ShowDialog();
            }
        }

        EasyHttp.Http.HttpClient client = new HttpClient();

        public string GetAnswer(string question)
        {
            var response = client.Get(Config.NlpServerUrl, new { text = question });
            LogHelper.Log(response.RawText);
            return response.RawText;
        }
        
        private void InvokeScript(string scriptName, params object[] objects)
        {
            if (htmlDocument != null)
            {
                if (objects == null || objects.Length < 1)
                {
                    var res = htmlDocument.InvokeScript(scriptName);
                }
                else
                {
                    var res = htmlDocument.InvokeScript(scriptName, objects);
                }
            }
        }
      

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            Invoke(new MethodInvoker(() =>
            {
                InvokeScript("setCurrentQuestion", "你好!");
            }));
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            this.Close();
            //_mainFrm.GoPrevForm();
        }

        private void QAFrm_FormClosed(object sender, FormClosedEventArgs e)
        {
            StopRobot();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if ((DateTime.Now - lastHasWord).TotalMinutes > 2)
            {
                this.timer1.Stop();
                StopRobot();
                WelcomeFrm frm = new WelcomeFrm();
                frm.ShowDialog();
                StartRobot();
                StartNewRecord(); //录入
            }
        }

        private void picRobotState_Click(object sender, EventArgs e)
        {
            var tag = this.picRobotState.Tag.ToString();
            if (tag == "speak")
            {
                RobotDriver.Instance.StopSpeak();
                StartNewRecord(); 
            }
            else
            {
                EndRecord();
                RobotDriver.Instance.StartSpeak(nameof(QAFrm), "您有什么问题?");
            }
        }
    }
}
